<template>
    <div class="home-page">
        <!-- 自定义导航栏 -->
        <div class="nav-custom">
            <div class="custom-title">
                <div class="title-logo"></div>
                <div class="title-tip">
                    <span>线上集市就选星辰</span>
                </div>
            </div>
            <div class="custom-search">
                <SvgIcon name="search" color="#9195a3" width="0.7em" height="0.7em"></SvgIcon>
                <input placeholder="搜索商品" type="text" @focus="inputOnFocus" />
                <SvgIcon name="code" color="#9195a3" width="0.5em" height="0.5em" style="position: relative; top:-2px;"></SvgIcon>
            </div>
        </div>
        <!-- 底部tabbar全局组件 -->
        <TabBar></TabBar>
        <div class="page-content" ref="divScrollRef">
            <div class="content-swiper">
                <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
                    <van-swipe-item v-for="item,index in bannerList" :key="index">
                        <img :src="item.imgUrl" alt="轮播图">
                    </van-swipe-item>
                </van-swipe>
            </div>
            <div class="content-category">
                <div class="category-item" v-for="item,index in homeCategory" :key="index">
                    <img :src="item.icon" alt="">
                    <span>{{ item.name }}</span>
                </div>
            </div>
            <!-- 平台活动部分 -->
            <div class="content-hot">
                <!-- 星辰秒杀部分 -->
                <div class="hot-seckill">
                    <div class="seckill-left">
                        <img class="left-seckill-img" src="/src/assets/images/icons/星辰秒杀.png" alt="">
                        <span class="left-seckill-tip">限时低价</span>
                        <div class="left-seckill-btn">
                            <span class="btn-text">去抢购</span>
                            <img class="btn-img" src="/src/assets/images/icons/arrow_right.png" alt="">
                        </div>
                    </div>
                    <div class="seckill-right">
                        <div class="right-item" v-for="item in seckillProduct" :key="item.productId">
                            <img class="item-img" :src="item.productImg" alt="">
                            <span class="item-price">￥{{ item.price }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 商品推送 分页加载商品数据-->
            <ProductList ref="ProductListRef"></ProductList>
        </div>
    </div>
</template>

<script setup lang='ts'>
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue';
import TabBar from '@/components/TabBar/TabBar.vue';
import ProductList from "@/components/ProductList/ProductList.vue";
import { ref, onBeforeUnmount, onMounted, getCurrentInstance, onActivated, onDeactivated } from "vue";
//引入vant4组件
import { Swipe as VanSwipe, SwipeItem as VanSwipeItem, showToast } from "vant";
//@ts-ignore引入请求函数
import { reqCarouselList, reqAllProductList } from "@/api/home/index.ts";
//引入数据类型约束
import type { carouselDataType } from "@/api/home/type.ts";
import router from '@/router';


//主界面的scrollDiv实例
const divScrollRef = ref();
//展示商品组件实例
const ProductListRef = ref();  //getGuessLikeList
//当前组件实例
const instance:any = getCurrentInstance();
//首页轮播图数据
const bannerList = ref<carouselDataType[]>([]);
//前台分类数据
const homeCategory = ref([
    {id:1,name:"星辰超市",icon:"/src/assets/images/home_category/超市.png"},{id:2,name:"潮流服饰",icon:"/src/assets/images/home_category/潮流服饰.png"},
    {id:3,name:"百亿补贴",icon:"/src/assets/images/home_category/百亿补贴.png"},{id:4,name:"充值中心",icon:"/src/assets/images/home_category/充值中心.png"},
    {id:5,name:"会员福利",icon:"/src/assets/images/home_category/星辰会员.png"},{id:6,name:"星辰数码",icon:"/src/assets/images/home_category/数码.png"},
    {id:7,name:"优品二手",icon:"/src/assets/images/home_category/优品二手.png"},{id:8,name:"星辰进口",icon:"/src/assets/images/home_category/星辰进口.png"},
    {id:9,name:"星辰拍卖",icon:"/src/assets/images/home_category/星辰拍卖.png"},{id:1,name:"星辰生鲜",icon:"/src/assets/images/home_category/星辰生鲜.png"}
]);
//秒杀专区的商品
let seckillProduct = ref<any>([]);
//请求所有的商品数据，采用随机筛选的方式从中选出4条商品数据作为“秒杀商品”
const getSeckillProduct = async () => {
    //获取所有的商品数据
    let res = await reqAllProductList();
    console.log('获取所有商品数据api',res);
    let total = res.result.total;
    //随机选取四条
    let seckillSet = new Set();
    for(let i = 0; seckillSet.size < 4 && i < (total -1); i++){
        let randomIndex = Math.floor(Math.random() * total);
        if(!seckillSet.has(res.result.rows[randomIndex])){
            seckillSet.add(res.result.rows[randomIndex]);
        }
    }
    let list:any = Array(...seckillSet);
    let seckillList = new Array();
    list.forEach(item => {
        let price = item.commercialSpecificationList[0].commodityPrice;
        for(let j = 1; j < item.commercialSpecificationList.length; j++){
            if(item.commercialSpecificationList[j].commodityPrice < price){
                price = item.commercialSpecificationList[j].commodityPrice;
            }
        }
        seckillList.push({
            price:price.toFixed(2),
            productId:item.productId,
            productImg:item.productImgs.split(",")[0]
        })
    })
    //赋值
    seckillProduct.value = seckillList;
}
//定时器实例
let timer:any = null;
let isFirst = true;
//当前页面滚动条位置
let scroll_top = ref(0);

//生命周期
onMounted(() => {
    //获取轮播图数据
    getHomeBannerList();
    //获取秒杀商品数据
    getSeckillProduct();
});

//判断滚动条距底部距离，实现加载更多
const getMoreGuessList = () => {
    scroll_top.value =  divScrollRef.value.scrollTop;  //存储滚动条位置
    //滚动条即将到达底部
    if(isFirst){
        //执行
        if(divScrollRef.value.clientHeight + divScrollRef.value.scrollTop + 20 >= divScrollRef.value.scrollHeight){
            //加载更多猜你喜欢数据
            ProductListRef.value.getProductList();
        }
        isFirst = false;
        return;
    }
    if(timer !== null){
        clearTimeout(timer);
    }
    timer = setTimeout(()=>{
        //执行
        if(divScrollRef.value.clientHeight + divScrollRef.value.scrollTop + 20 >= divScrollRef.value.scrollHeight){
            //加载更多猜你喜欢数据
            ProductListRef.value.getProductList();
        }
    },300)
}
//window监听滚动事件
window.addEventListener("scroll",getMoreGuessList,true);

//获取首页轮播图数据
const getHomeBannerList = async () => {
    let res = await reqCarouselList();
    bannerList.value = res.result.rows;
    console.log('首页轮播图数据api',res);
}

//点击热门推荐图片跳转到推荐页面:特惠推荐type=1,爆款推荐type=2,...
const navigateToPage = (type:number) => {
    console.log({type});
}

//kepp-alive缓存生命周期
onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  window.addEventListener("scroll",getMoreGuessList,true);
  divScrollRef.value.scrollTop = scroll_top.value;  //从缓存进入页面重新赋值滚动条位置
  console.log('home component enter page!');
})

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  window.removeEventListener("scroll",getMoreGuessList,true);
  console.log('home component enter cache!"62226 2029000 458 0099"');
})
//62226 2029000 458 0099

//顶部输入框获取焦点事件
function inputOnFocus () {
    showToast("即将跳转...");
    //跳转到搜索页
    setTimeout(()=>{
        router.push("/search");
    },300)
}

//生命周期
onBeforeUnmount(()=>{
    console.log('home component will be over!');
    window.removeEventListener("scroll",getMoreGuessList,true);
})
</script>

<style scoped lang='less'>
//自定义导航栏
.nav-custom{
    width: 375px;
    height: 85px;
    position: fixed;
    top:0;
    padding:5px;
    background-color: #dc0f0f;
    z-index: 99;

    .custom-title{
        width: 375px;
        display: flex;
        margin: 10px 0;

        .title-logo{
            width: 110px;
            height:24px;
            background: url("../../assets/images/logo.png") no-repeat;
            background-size:contain;
        }
        .title-tip{
            width:110px;
            padding-left:10px;
            text-align: center;
            line-height: 20px;
            border-left:1px solid #fff;

            span{
                font-size:12px;
                color:#fff;
            }
        }
    }
    .custom-search{
        width: 355px;
        height: 28px;
        border-radius: 15px;
        padding: 0 8px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        background-color: #fff;

        input{
            width: 280px;
            height: 22px;
            margin: 0 10px;
            font-size: 14px;
            color: #9195a3;
            background-color: #fff;
            border: none;
            outline: none;

            &::placeholder{
                color: #9195a3;
            }
        }
    }
}
//主体部分
.page-content{
    position: relative;
    top:85px;
    height: calc(100vh - 85px - 60px);
    background-color: #f4eaea;
    overflow: scroll;
    //轮播图部分
    .content-swiper{
        height: 150px;

        img{
            width: 375px;
            height: 150px;
        }
    }
    //商品分类部分
    .content-category{
        width: 375px;
        height: 170px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-wrap: wrap;
        background: #fff;
        .category-item{
            width: 50px;
            height: 80px;
            margin: 3px 10px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            img{
                width: 40px;
                height: 40px;
            }
            span{
                margin-top: 8px;
                font-size: 12px;
                color: #44bb94;
            }
        }
    }
    //平台活动部分
    .content-hot{
        width: 375px;
        // height: 250px;

        /**活动秒杀部分 */
        .hot-seckill{
            width: 355px;
            height: 100px;
            margin: 8px 10px;
            padding: 3px;
            box-sizing: border-box;
            background-color: #dc0f0f;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .seckill-left{
                width: 90px;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                .left-seckill-img{
                    width: 85px;
                    height: 20px;
                }
                .left-seckill-tip{
                    font-size: 14px;
                    color: #fff;
                }
                .left-seckill-btn{
                    width: 70px;
                    height: 20px;
                    background: #fff;
                    border-radius: 10px;
                    display: flex;
                    justify-content: space-around;
                    align-items: center;
                    .btn-text{
                        font-size: 12px;
                        color: #dc0f0f;
                    }
                    .btn-img{
                        width: 12px;
                        height: 12px;
                    }
                }
            }
            .seckill-right{
                width: 265px;
                height: 98px;
                padding: 5px;
                background-color: #fff;
                border-radius: 10px;
                display: flex;
                align-items: center;
                .right-item{
                    width: 60px;
                    height: 80px;
                    margin: 0 2px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    align-items: center;
                    .item-img{
                        width: 55px;
                        height: 65px;
                    }
                    .item-price{
                        font-size: 10px;
                        color: #dc0f0f;
                    }
                }
            }
        }
    }
}
</style>